<?php

namespace common\helpers;

use Yii;
use yii\db\Exception;

/**
 * 公共的工具性方法.
 * User: paul
 * Date: 2017/1/4 0004
 * Time: 17:58
 */
class Helper
{

    /**
     * 生成不同时间间隔的sql区间，供mysql查询不同的时间间隔的数据
     * @param $type
     * @return string
     */
    public static function intervalDate($type) {
        switch ($type) {
            case 1: // 今天
                $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end = mktime(0, 0, 0, date('m'), date('d')+1, date('Y'))-1;
                break;
            case 3: // 本月
                $start = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $end = mktime(0, 0, 0, date('m')+1, 1, date('Y'))-1;
                break;
            case 4: // 本年
                $start = mktime(0, 0, 0, 1, 1, date('Y'));
                $end = mktime(0, 0, 0, 1, 1, date('Y')+1)-1;
                break;
            case 5: // 昨天
                $start = mktime(0, 0, 0, date('m'), date('d')-1, date('Y'));
                $end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                break;
            case 9: // 前七天
                $start = mktime(0, 0, 0, date('m'), date('d')-6, date('Y'));
                $end = mktime(date('H'), date('m'), date('s'), date('m'), date('d'), date('Y'));
                break;
            default:
                $start = ''; $end = '';
        }

        return " between $start and $end ";
    }

    /**
     * ---------------------------------------
     * 上传base64格式的图片
     * @param string $imgBase64 图片的base64编码
     * @return mixed
     * ---------------------------------------
     */
    public static function uploadImage($imgBase64,$folder = 'image')
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgBase64, $result)){
            $type = $result[2];
            $type = $type == 'jpeg' ? 'jpg' : $type;
            $fileName = time() . rand( 1 , 1000 ) . "." . $type;
            /* 以年月创建目录 */
            $dir = date('Y-m-d', time());
            $path = Yii::$app->params['upload']['img'] . $folder . '/' . $dir;

            if (!file_exists($path)) {
                mkdir($path, 0777);
            }

            $fileName = $dir.'/'.$fileName;


            if (file_put_contents(dirname($path) . '/' . $fileName, base64_decode(str_replace($result[1], '', $imgBase64)))) {
                return $fileName;
            }

        }

        return false;
    }


    /**
     * ---------------------------------------
     * 生成 图片路径
     * @param string $url 图片相对路径，一般为“201605/1235654.jpg”
     * @param string $params 生成链接时的附加测试，例如长宽等
     * @param bool $isUrl 是否生成php文档形式的url
     * @return string
     * ---------------------------------------
     */
    public static function src($url, $params = '', $isUrl = false,$folder = 'dimg')
    {
        if (mb_strpos($url, 'http') !== false) {
            return $url;
        }

        if ($isUrl === false) {
            // 特别说明：folder默认为dimg，但是不能影响编辑器上传到‘editor’的很多图片展示
            $url = str_replace('/static/attachment/','',$url);
            if (mb_strpos($url, 'editor') === false) {
                //切割成数组等于2 表示默认的传入（即数据库保存的）图片地址格式为：2017-07-05/2jkk2adc2dal2.jpg
                if(count(explode('/',$url)) == 2) $url = $folder . '/' . $url;
            }
            return Yii::$app->params['upload']['url'] . $url;
        }
        $query = 'path=' . $url;
        if ($params) {
            $query .= '&' . $params;
        }
        if (Yii::$app->params['storage_encrypt']) {
            $query = 'path=' . base64_encode($query);

        }

        return Yii::getAlias('@storageUrl') . '/index.ph    p?' . $query;
    }

    public static function parseImg($url){

        if(stripos($url,'http') !== false || stripos($url,'https') != false) return $url;

        return Yii::getAlias('@imgDomain').$url;
    }

    public static function downloadImage($uri,$fileName,$from,$folder='star'){
        ob_start();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        if($from){
            curl_setopt($ch,CURLOPT_REFERER, $from);
        }
        curl_exec($ch);
        $img = ob_get_contents();
        curl_close($ch);
        ob_clean();

        $type = 'jpg';

        if(empty($fileName)) $fileName = uniqid();
        $filePath = Helper::createImagePath($folder);
        $filePath = $filePath.$fileName.$type;


        $fs = fopen($filePath,"w+");
        fwrite($fs,$img);
        fclose($fs);

        return Helper::src($filePath);
    }

    public static function createImagePath($folder='images'){

    }



}